﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.System;
//modified by jeff.yuan 增加通过URL传查询条件，传客户和日期
public partial class Order_List : PageBase
{
    private const string NEW_PAGE = "Customer_Select.aspx";
    private OrgainzationManager orgManager = new OrgainzationManager();
    protected void Page_Load(object sender, EventArgs e)
    {
        
       
        if (!IsPostBack)
        {
            DataBind();
            if (txtHidOrg.Value == "")
            {
                this.txtHidOrg.Value = OrgHidValue;
                this.txtOrg.Text = OrgShowValue;
                OrgHelper.BindChiansDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlChains);
                var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
                if (data.Rows.Count != 1)
                {
                    OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlUser);
                }
                else
                {
                    Person person = new PersonManager().Load(MyStateManager.PersonID);
                    ddlUser.Items.Add(new ListItem(person.Name, MyStateManager.UserID.ToString()));
                }

            }
            InitForm();
            txtEnd.Text = DateTime.Now.ToShortDateString();
            txtStart.Text = DateTime.Now.ToShortDateString();
            InitConditionByUrl();
            LoadConditions();
            BindGrid();

           

          
        }
    }
    protected void InitConditionByUrl()
    {

        if (Request.QueryString["userid"] != null)
        {
            this.ddlUser.SelectedIndex = ddlUser.Items.IndexOf(ddlUser.Items.FindByValue(Request.QueryString["userid"].ToString()));
        }
        DateTime dt = new DateTime();
        if (Request.QueryString["visittime"] != "" &&
            DateTime.TryParse(Request.QueryString["visittime"], out dt))
        {
            this.txtStart.Text = dt.ToShortDateString();
            this.txtEnd.Text = dt.ToShortDateString();
        }
    }
    private void InitForm()
    {
        USER_CHAINS userChains = new UserManager().LoadChainsByUser(this.MyStateManager.UserID);

        //经销商用户
        if (userChains != null)
        {
            txtOrg.Text = new OrgainzationManager().Load(MyStateManager.OrgID).NAME;
            txtHidOrg.Value = "'" + MyStateManager.OrgID + "'";
            OrgHelper.BindChiansDDL(MyStateManager.DomainID, txtHidOrg.Value, ddlChains);
            ddlChains.SelectedValue = userChains.CHAINSID.ToString();
            ddlChains.Enabled = false;
            OrgHelper.BindUsersDDL(MyStateManager.DomainID, txtHidOrg.Value, ddlUser);
        }

        DictionaryItemsManager dim = new DictionaryItemsManager();

        //销售渠道
        ddlChannel.DataTextField = "Name";
        ddlChannel.DataValueField = "DictionaryItemId";
        ddlChannel.DataSource = dim.GetItemList(DictionaryEnum.CustomerChannel, this.MyStateManager.DomainID);
        ddlChannel.DataBind();
        ddlChannel.Items.Insert(0, new ListItem("-所有-", ""));

        //绑定订单状态
        string[] names = Enum.GetNames(typeof(Jumpton.SFA.Server.Entity.EOderStatus));
        int[] values = (int[])Enum.GetValues(typeof(Jumpton.SFA.Server.Entity.EOderStatus));
        for (int i = 0; i < names.Length; i++)
        {
            ddlStatus.Items.Add(new ListItem(names[i], values[i].ToString()));
        }
        ddlStatus.Items.Insert(0, new ListItem("--所有--", ""));

        //绑定订单来源
        ddlOrderForm.DataTextField = "Name";
        ddlOrderForm.DataValueField = "DictionaryItemId";
        ddlOrderForm.DataSource = dim.GetItemList(DictionaryEnum.OrderForm, this.MyStateManager.DomainID);
        ddlOrderForm.DataBind();
        ddlOrderForm.Items.Insert(0, new ListItem("手机上传", "0"));
        ddlOrderForm.Items.Insert(0, new ListItem("-所有-", ""));

        names = Enum.GetNames(typeof(Jumpton.SFA.Server.Entity.EOrderType));
        values = (int[])Enum.GetValues(typeof(Jumpton.SFA.Server.Entity.EOrderType));
        for (int i = 0; i < names.Length; i++)
        {
            ddlOrderType.Items.Add(new ListItem(names[i], values[i].ToString()));
        }
        ddlOrderType.Items.Insert(0, new ListItem("--所有--", ""));
    }

    private void BindGrid()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder(" ");

        if (!string.IsNullOrEmpty(txtHidOrg.Value))
        {
            sb.Append(string.Format(" AND OH.ORG_ID IN ({0})", txtHidOrg.Value));
        }
        else
        {
            return;
        }
        if (ddlChains.SelectedValue != string.Empty)
        {
            sb.Append(" And CHAINS.ID = '" + ddlChains.SelectedValue + "' ");
        }
        if (ddlChannel.SelectedValue != string.Empty)
        {
            sb.Append(" AND C.LOCAL_LEVEL1_CODE =  '" + ddlChannel.SelectedValue + "'  ");
        }
        if (ddlUser.SelectedValue != string.Empty)
        {
            sb.Append(" AND OH.person_id =(select person_id from users where users.id='" + ddlUser.SelectedValue + "')  ");
        }
        if (txtCode.Text != string.Empty)
        {
            sb.Append(" AND (C.[CODE] LIKE '%" + txtCode.Text.Trim() + "%' or C.[NAME] LIKE '%" + txtCode.Text.Trim() + "%' or CI.[ADDRESS_LINE] like  '%" + txtCode.Text.Trim() + "%' "
                + " or C.default_ship_to_code LIKE '%" + txtCode.Text.Trim() + "%' or  "
                + " CI.telephone LIKE '%" + txtCode.Text.Trim() + "%' or  CI.fax LIKE '%" + txtCode.Text.Trim() + "%' "
                + " )    ");
        }

        if (txtStart.Text != string.Empty)
        {
            sb.Append(" AND DATEDIFF(DD,dbo.[GetDateTimeByBigint](OH.ORDER_date),'" + DateTime.Parse(txtStart.Text).ToShortDateString() + "')<=0 ");
        }
        if (txtEnd.Text != string.Empty)
        {
            sb.Append(" AND DATEDIFF(DD,dbo.[GetDateTimeByBigint](OH.ORDER_date),'" + DateTime.Parse(txtEnd.Text).ToShortDateString() + "')>=0 ");
        }
        if (ddlStatus.SelectedValue != string.Empty)
        {
            sb.Append(" AND  OH.STATUS='" + ddlStatus.SelectedValue + "'  ");
        }
        //else
        //{
        //    sb.Append(" AND  OH.STATUS<>'" + ((int)EOderStatus.已取消).ToString() + "'  ");
        //}
        if (txtOrderNo.Text != string.Empty)
        {
            sb.Append(" AND OH.ORDER_NO LIKE '%" + txtOrderNo.Text + "%' ");
        }
        if (this.ddlOrderType.SelectedValue != string.Empty)
        {
            sb.Append(" AND  OH.OrderType='" + ddlOrderType.SelectedValue + "'  ");
        }
        if (this.drpCancelled.SelectedValue != string.Empty)
        {
            //有效
            sb.Append(string.Format(" AND OH.CANCELLED='{0}' ", drpCancelled.SelectedValue));
        }
        if (ddlOrderForm.SelectedValue != string.Empty)
        {
            if (ddlOrderForm.SelectedValue == "0")
                sb.Append(" AND OH.ORDER_FORM IS NULL");
            else
                sb.Append(string.Format(" AND OH.ORDER_FORM='{0}' ", ddlOrderForm.SelectedValue));
        }
       
        DataSet ds = OrderHeaderManager.SearchOrderList(MyStateManager.DomainID, sb.ToString());
        if (ds != null && ds.Tables.Count > 0)
        {
            gvChannelType.DataSource = ds.Tables[0];
            gvChannelType.DataBind();
        }

    }

    protected void btnQuery_Click(object sender, EventArgs e)
    {
        BindGrid();
        SaveConditions();
    }

    public void GridViewToolbarUserControl1_OnGVTBSetColumnsButtonEvent(object sender, EventArgs e)
    {
        BindGrid();
    }

    protected void gvChannelType_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvChannelType.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    int rowCount = gvChannelType.Columns.Count;
        //    if (e.Row.Cells[rowCount - 1].Text.Contains("N"))
        //    {
        //        e.Row.Cells[rowCount - 1].Text = "<font size='3' color='green'>√</font>";
        //    }else
        //        e.Row.Cells[rowCount - 1].Text = "<font size='3' color='red'>×</font>";

        //}
    }


    protected void SaveConditions()
    {
        string pagename = "order_list";
        Session[pagename + "ddluser"] = ddlUser.SelectedValue;
        Session[pagename + "ddlordertype"] = ddlOrderType.SelectedValue;
        Session[pagename + "ddlchains"] = ddlChains.SelectedValue;
        Session[pagename + "txtstart"] = txtStart.Text;
        Session[pagename + "txtend"] = txtEnd.Text;
        Session[pagename + "txtcode"] = txtCode.Text;
        Session[pagename + "ddlchannel"] = ddlChannel.SelectedValue;
        Session[pagename + "ddlstatus"] = ddlStatus.SelectedValue;
        Session[pagename + "txtorderno"] = txtOrderNo.Text;
        Session[pagename + "drpcancelled"] = drpCancelled.SelectedValue;
        Session[pagename + "isactive"] = "1";

    }
    protected void LoadConditions()
    {
        string pagename = "order_list";
        if (Session[pagename + "isactive"] != null && Session[pagename + "isactive"].ToString() == "1")
        {
            try
            {
                ddlUser.SelectedValue = Session[pagename + "ddluser"].ToString();
                ddlOrderType.SelectedValue = Session[pagename + "ddlordertype"].ToString();
                ddlChains.SelectedValue = Session[pagename + "ddlchains"].ToString();
                txtStart.Text = Session[pagename + "txtstart"].ToString();
                txtEnd.Text = Session[pagename + "txtend"].ToString();
                txtCode.Text = Session[pagename + "txtcode"].ToString();
                ddlChannel.SelectedValue = Session[pagename + "ddlchannel"].ToString();
                ddlStatus.SelectedValue = Session[pagename + "ddlstatus"].ToString();
                txtOrderNo.Text = Session[pagename + "txtorderno"].ToString();
                drpCancelled.SelectedValue = Session[pagename + "drpcancelled"].ToString();
            }
            catch
            {
            }
            Session[pagename + "isactive"] = "0";
        }

    }
    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        ddlChains.Items.Clear();
        ddlUser.Items.Clear();

        if (!string.IsNullOrEmpty(txtHidChains.Value))
        {
            string[] options = txtHidChains.Value.Split('∮');
            

            for (int i = 0; i < options.Length; i++)
            {
                string[] item = options[i].Split('∞');
                ddlChains.Items.Add(new ListItem(item[1], item[0]));
            }
      
        }

        //判断当前的人所在的部门是不是最小的一级org
        var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
        if (data.Rows.Count != 1)
        {
            if (!string.IsNullOrEmpty(txtHidUsers.Value))
            {
                string[] options2 = txtHidUsers.Value.Split('∮');
                for (int i = 0; i < options2.Length; i++)
                {
                    string[] item2 = options2[i].Split('∞');
                    ddlUser.Items.Add(new ListItem(item2[1], item2[0]));
                }
            }
            ddlUser.Items.Insert(0, new ListItem("--所有--", ""));
        }
        else
        {
            Person person = new PersonManager().Load(MyStateManager.PersonID);
            ddlUser.Items.Add(new ListItem(person.Name,MyStateManager.UserID.ToString()));
        }
        ddlChains.Items.Insert(0, new ListItem("--所有--", ""));
        

    }
}
